/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fujitsu.nanjing.tieba.base.BaseService;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreBookmark;
import com.fujitsu.nanjing.tieba.ibator.CoreBookmarkCriteria;
import com.fujitsu.nanjing.tieba.model.Bookmark;

/**
 * BookmarkService.java
 * 
 * @author Administrator
 */
@Service
@Transactional
public class BookmarkService
		extends
			BaseService<CoreBookmark, CoreBookmarkCriteria> {
	@Resource
	private Bookmark bookmark;
	@Override
	public CoreBookmark findById(String id) {
		return bookmark.selectByPrimaryKey(Integer.parseInt(id));
	}

	@Override
	public CoreBookmark insert(CoreBookmark t) {
		t.setCreatetime(new Date());
		bookmark.insertSelective(t);
		return t;
	}

	@Override
	public void update(CoreBookmark t) {
		bookmark.updateByPrimaryKeySelective(t);

	}

	@Override
	public void delete(CoreBookmark t) {
		bookmark.deleteByPrimaryKey(t.getMarkid());

	}
	public List<CoreBookmark> findFavorsByUserId(String userId, int offset) {
		CoreBookmarkCriteria example = new CoreBookmarkCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认排序条件);
		example.createCriteria().andUseridEqualTo(userId);
		return bookmark.selectByExample(example);
	}
	public int countByUserId(String userId) {
		CoreBookmarkCriteria example = new CoreBookmarkCriteria();
		example.createCriteria().andUseridEqualTo(userId);
		return bookmark.countByExample(example);
	}
	/**
	 * 根据用户获取<code>书签</code>总页数
	 * */
	public int findPageCountByUserId(String userId) {
		int pageCount = (int) Math.ceil((double) countByUserId(userId)
				/ CommonParamter.默认分页长度);
		if (pageCount == 0) {
			pageCount = 1;
		}
		return pageCount;
	}

	public void deleteFavors(String markId) {
		if (markId != null) {
			String[] markIds = markId.split(",");
			for (String mark : markIds) {
				delete(findById(mark));
			}
		}
	}

}
